package com.example.mobilesafe.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.example.mobilesafe.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class ContactListActivity extends AppCompatActivity {

    /**
     * ListView
     */
    private ListView lv_contact;

    /**
     * 存放联系人的集合
     */
    private List<HashMap<String,String>> mContactList = new ArrayList<>();

    /**
     * 适配器对象
     */
    private MyAdapter mAdapter = new MyAdapter();

    /**
     * Handler对象
     */
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            // 10.填充数据适配器
            MyAdapter adapter = new MyAdapter();
            lv_contact.setAdapter(adapter);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contact_list);

        // 初始化UI
        intiUI();

        // 初始化数据
        initData();
    }

    /**
     * 1.初始化UI
     */
    private void intiUI() {
        lv_contact = findViewById(R.id.lv_contact);
        if (ContextCompat.checkSelfPermission(ContactListActivity.this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(ContactListActivity.this, new String[]{Manifest.permission.READ_CONTACTS}, 1);
        }
        lv_contact.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // 1.获取点中条目的索引，指向集合中的对象
                if (mAdapter != null){
                    HashMap<String, String> item = mAdapter.getItem(position);
                    // 2.获取当前条目指向集合对应的电话号码
                    String phone = item.get("phone");
                    // 3.此电话号码需要给第三个导航界面使用
                    Intent intent = new Intent();
                    intent.putExtra("phone",phone);
                    setResult(0,intent);
                    // 4.结束当前Activity
                    finish();
                }
            }
        });
    }


    /**
     * 2.初始化数据
     */
    private void initData() {
        // 读取联系人是一个耗时操作，可以放在线程中执行
        new Thread(){
            @Override
            public void run() {
                // 1.获取内容解析器对象
                ContentResolver contentResolver = getContentResolver();
                // 2.封装查询过程
                Cursor cursor = contentResolver.query(
                        Uri.parse("content://com.android.contacts/raw_contacts"),
                        new String[]{"contact_id"},
                        null, null, null);
                mContactList.clear();
                // 3.循环游标，直到没有数据为止
                while (cursor.moveToNext()){
                    String id = cursor.getString(0);
                    Log.i("ContactListActivity",id);
                    // 4.根据用户唯一性id值，查询data表和mimetype表生成的视图，获取data以及mimetype字段
                    Cursor indexCursor = contentResolver.query(
                            Uri.parse("content://com.android.contacts/data"),
                            new String[]{"data1", "mimetype"},
                            "raw_contact_id = ?", new String[]{id}, null);
                    HashMap<String, String> hashMap = new HashMap<>();
                    while (indexCursor.moveToNext()){
                        // 5.循环获取每一个联系人的电话号码以及姓名
                        String data1 = indexCursor.getString(0);
                        String mimetype = indexCursor.getString(1);
                        // 区分类型填充数据
                        if (mimetype.equals("vnd.android.cursor.item/phone_v2")){
                            // 数据非空
                            if (!TextUtils.isEmpty(data1)){
                                hashMap.put("phone",data1);
                            }
                        }else if(mimetype.equals("vnd.android.cursor.item/name")){
                            // 数据非空
                            if (!TextUtils.isEmpty(data1)){
                                hashMap.put("name",data1);
                            }
                        }
                    }
                    // 6.关闭游标
                    indexCursor.close();
                    // 7.添加数据
                    mContactList.add(hashMap);
                }
                // 8.关闭游标
                cursor.close();
                // 9.发送消息给主线程
                mHandler.sendEmptyMessage(0);
            }
        }.start();
    }

    /**
     * 3.数据适配器内部类
     */
    private class MyAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return mContactList.size();
        }

        @Override
        public HashMap<String, String> getItem(int position) {
            return mContactList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = View.inflate(getApplicationContext(), R.layout.listview_contact_item, null);
            TextView tv_name = view.findViewById(R.id.tv_name);
            TextView tv_phone = view.findViewById(R.id.tv_phone);
            tv_name.setText(getItem(position).get("name"));
            tv_phone.setText(getItem(position).get("phone"));
            return view;
        }
    }
}